package top.hkyzf.study.leetcode.graph;

import org.junit.Test;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author 朱峰
 * @date 2022-1-27 11:52
 */
public class _01矩阵_542 {
    public int[][] updateMatrix(int[][] mat) {
        int m = mat.length;
        int n = mat[0].length;
        Queue<int[]> queue = new LinkedList<>();
        boolean[][] watch = new boolean[m][n];
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[0].length; j++) {
                if (mat[i][j] == 0) {
                    queue.offer(new int[]{i, j});
                    watch[i][j] = true;
                }
            }
        }
        bfs(mat, watch, queue);
        return mat;
    }

    private void bfs(int[][] mat, boolean[][] watch, Queue<int[]> queue) {
        // 方向
        int[] dx = new int[] {-1, 1, 0, 0};
        int[] dy = new int[] {0, 0, -1, 1};
        int value = 0;
        while (!queue.isEmpty()) {
            int[] ints = queue.poll();
            // 4 个方向
            for (int i = 0; i < 4; i++) {
                int x = ints[0] + dx[i];
                int y = ints[1] + dy[i];
                if (x >= 0 && x < mat.length && y >= 0 && y < mat[0].length && !watch[x][y]) {
                    queue.offer(new int[]{x, y});
                    mat[x][y] = mat[ints[0]][ints[1]] + 1;
                    watch[x][y] = true;
                }
            }
        }
    }

    @Test
    public void testUpdateMatrix () {
        int[][] mat = {{0,0,0},{0,1,0},{1,1,1}};
        int[][] matrix = updateMatrix(mat);
        for (int[] matrix_x : matrix) {
            System.out.println(Arrays.toString(matrix_x));
        }
    }
}
